#include <stdio.h>
#include <stdlib.h>

typedef struct Nodebll{
    int value;  // data 
    struct Nodebll *front;  // front pt
    struct Nodebll  *next;  // next pt
}BiLinkList;

BiLinkList *create_bilinklist(int n){
    BiLinkList *head, *node, *end;
    head = (BiLinkList *)malloc(sizeof(BiLinkList));
    end = (BiLinkList *)malloc(sizeof(BiLinkList));
    head->front = 0;
    head->next = head->front = 0;
    end = head;
    for (int i=0; i<n; ++i){
        node = (BiLinkList *)malloc(sizeof(BiLinkList));
        node->value = i;
        node->front = end;
        end->next = node;
        end = node;
    }
    end->next = 0;
    return head;
}

void modify_bilinklist(BiLinkList *list, int n, int val){
    // 输入n为需要修改的第n个节点
    // val为修改后的值
    BiLinkList *l = list;
    int i = 0;
    while (i < n && l != 0){
        l = l->next;
        ++i;
    }
    if (l != 0){
        l->value = val;
    }else{
        printf("Node doesn't exist! \n");
    }
}

void delete_node(BiLinkList *list, int n){
    BiLinkList *l = list;
    int i = 0;
    while (i < n && l != 0){
        l = l->next;
        ++i;
    }
    if (l != 0){
        l->front->next = l->next;
        if (l->next!=0) l->next->front = l->front;
        free(l);
    }else{
        printf("Node doesn't exist! \n");
    }
}

void insert_node(BiLinkList *list, int n, int val){
    // 在第n节点后插入一个节点赋值val
    BiLinkList *l = list, *temp;

    int i = 0;
    while (i < n-1 && l != 0){
        l = l->next;
        ++i;
    }
    // 此时指针l指向第n个节点
    if (l != 0){
        temp = (BiLinkList *)malloc(sizeof(BiLinkList));  
        temp->value = val;
        temp->next = l->next;
        temp->front = l;
        l->next->front = temp;
        l->next = temp;
    }else{
        printf("Node does't exist. \n");
    }
}

void print_bilinklist(BiLinkList *bilist){
    BiLinkList *bl = bilist;

    if (bl->next == 0) printf("EMPTY! \n");
    while (bl->next != 0){
        bl = bl->next;
        printf("%d ", bl->value);
    }
    printf("\n");
    while (bl->front != 0){
        printf("%d ", bl->value);
        bl = bl->front;
    }
    printf("\n");
}

int main(void){
    int n;
    BiLinkList * bilist;
    printf("input the length of bll: \n");
    scanf("%d", &n);
    bilist = create_bilinklist(n);
    print_bilinklist(bilist);

    modify_bilinklist(bilist, 6, 55);
    print_bilinklist(bilist);

    delete_node(bilist, 6);
    print_bilinklist(bilist);

    insert_node(bilist, 6, 555);
    print_bilinklist(bilist);

    for (int i=0; i<n; ++i){
        delete_node(bilist, 1);
        print_bilinklist(bilist);
    }
    return 0;
}
